class Reservation < ActiveRecord::Base
  belongs_to :post
  belongs_to :member
  
  
  validates_presence_of :post_id, :member_id
  
  validates_date_time :start_date, :before => Proc.new {14.day.from_now}, :before_message => 'You can\'t make bookings more than 14 days in the future'
  
  validates_each :end_date do |record, attr, value|
    min_reservation = record.post.category.min_reservation
    record.errors.add attr, "Bookings have to be at least #{(min_reservation + 1).to_s} minutes long" if record.start_date.advance(:minutes => min_reservation) > value
    record.errors.add attr, 'Sorry, we close at 6pm' if (value.hour >= 18 and value.min > 01)
    record.errors.add attr, '9am is the earliest you can book' if (value.hour < 9)
    record.errors.add attr, 'Sorry, we\'re closed on Sundays and Saturdays' if (value.wday == 0 or value.wday == 6)
  end
  
  validates_each :start_date do |record, attr, value|
    record.errors.add attr, 'Must be before end Date' if (record.end_date < value)
    record.errors.add attr, 'Sorry, we close at 6pm' if (value.hour >= 18 and value.min > 01)
    record.errors.add attr, '9am is the earliest you can book' if (value.hour < 9)
    record.errors.add attr, 'Sorry, we\'re closed on Sundays and Saturdays' if (value.wday == 0 or value.wday == 6)
  end
  
  acts_as_state_machine :initial => :cart
  
  state :cart
  state :awaiting_payment
  state :paid
  state :payment_failed
  state :returned
  
  event :confirm do
    transitions :from => :cart, :to => :awaiting_payment
  end
  
  event :credited do
    transitions :from => :awaiting_payment, :to => :paid
    transitions :from => :payment_failed, :to => :paid
    transitions :from => :cart, :to => :paid
  end
  
  event :failure do 
    transitions :from => :awaiting_payement, :to => :payement_failed
    transitions :from => :paid, :to => :payement_failed
  end
  
  event :returned do
    transitions :from => :paid, :to => :returned
  end
  
  def credit_needed
    # hours reserved x hourly cost of post
    (self.user_end_date - self.start_date) * self.post.category.member_cost / 3600
  end
  
  def user_end_date
    self.end_date + 60
  end
  
  def set_dates_and_hours(reservation_params, starthour_params, endhour_params)
    self.start_date = Time.parse(reservation_params["start_date"])
    #set hour
    self.start_date = self.start_date.change(:hour => starthour_params[:hour], :min => starthour_params[:min])

    self.end_date = self.start_date
    #set hour
    self.end_date = self.end_date.change(:hour => endhour_params[:hour], :min => endhour_params[:min])
  end
  
end
